import Vue from 'vue'

import * as api from '@/api/template/userSelector'

/**
 * @description 选人控件
 * @param { int } allowNum  最大可选人员数量
 * @param { array } select_userids 默认勾选的人员id ['test','test1']
 * @param { boolean } diy 是否指定可选择的人员
 * @param { array } diy_userids 指定的人员列表id ['test','test1']
 */
function show(params) {

  // HTML
  var domStr =
    `<style>
	#ray_component_div .dpt_row:hover{
		background-color: #F1F1F2;
		cursor: pointer;
	}

	#ray_component_div .down_button{
		color:#9FA0A2;
	}

	#ray_component_div .gudie_button{
		color:#303133;
		padding:0px
	}

	#ray_component_div .el-input__inner {
		border:none;
		padding:0;
	}

	#ray_component_div .el-checkbox__inner{
		border-radius: 50%;
	}

  #ray_component_div .el-checkbox.is-bordered{
    border:1px solid #F8F8F8
  }
</style>
    	<vxe-modal id="selectUser" title="选人" v-model="showFlag" width="700" height="500" remember storage>
		  <template #default>
			  <el-row>
				  <el-col :span="12" style="border-right:1px solid #E6E6E6;height:410px;padding-right:10px">
				  	<div style="height:390px">
					  	<el-autocomplete
					  	  v-if="!diy"
						  class="inline-input"
						  v-model="state"
						  style="width:100%;"
						  :fetch-suggestions="querySearch"
						  :trigger-on-focus="false"
						  placeholder="根据名字，拼音，登录名进行搜索"
						  @select="handleSelect">
						  <template slot-scope="{item}">
						    <div style="line-height:15px;padding-top:5px;text-overflow: ellipsis;overflow: hidden;">{{ item.username }} <span style="color:#E6E6E6;font-size:12px;float:right">{{item.userid}}</span></div>
						    <div style="margin-top:10px;padding-bottom:5px;line-height:15px;font-size:12px;color:#b4b4b4;border-bottom:1px solid #E6E6E6;overflow: hidden;white-space:normal;">
						    	{{ item.dptName }}
						    </div>
						  </template>
						</el-autocomplete>
						<div style="margin-top:5px;height:330px;overflow:auto">
							<el-tag
							  style="margin-top:5px;margin-right:5px;margin-left:0px"
							  :key="item.userid"
							  v-for="item in selectUsers"
							  size="mini"
							  effect="dark"
							  closable
							  :disable-transitions="false"
							  @close="handleClose(item)">
							  {{item.username}}
							</el-tag>
						</div>
				  	</div>
					<el-button type="primary" size="mini" @click="confirm" :disabled="confirmStatu">确定({{selectNum}}/{{allowNum}})</el-button>
					<el-button size="mini" @click="close">取消</el-button>
				  </el-col>
				  <el-col :span="12" style="padding-left:10px" v-if="!diy">
				  	  <div v-if="index=='index'">
					  	  <div style="padding:2px 0px;"><el-button @click="zzjg" style="width:100%;border:none;text-align:left"><i class="el-icon-office-building"></i> 按组织架构选择</el-button></div>
				  	  	  <div style="padding:2px 0px;"><el-button @click="indexRole" style="width:100%;border:none;text-align:left"><i class="el-icon-user-solid"></i> 按角色选择</el-button></div>
					  	  <div style="padding:2px 0px;" v-for="item in myDpts"><el-button @click="indexDpt(item.no)" style="width:100%;border:none;text-align:left"><i class="el-icon-school"></i> {{item.name}}</el-button></div>
				  	  </div>
				  	  <el-page-header v-if="index!='index'" @back="goBack" title="" :content="header"></el-page-header>
				  	  <div v-if="index=='dpt'" style="height:370px;overflow:auto">
				  	  	<div style="margin-top:5px">
				  	  		<span v-for="(item,index) in guide">
				  	  			<span v-if="index!=0" style="padding-left:5px">/</span>
				  	  			<el-button @click="gudieClick(item.no,index)" class="gudie_button" type="text" :disabled="item.id == dpt.id">{{item.name}}</el-button>
				  	  		</span>
				  	  	</div>
				  	  	<div style="padding:2px 0px;" v-for="(item,index) in c_dpts">
				  	  		<el-row type="flex" justify="space-between" class="dpt_row">
							  <el-col :span="18" style="padding:7px 20px"><i class="el-icon-school"></i> {{item.name}}</el-col>
							  <el-col :span="6"><el-divider direction="vertical"></el-divider><el-button type="text" class="down_button" @click="down(item.no)"><i class="el-icon-bottom"></i>下级</el-button></el-col>
							</el-row>
				  	  	</div>
                <div style="padding:2px 10px;">
                  <el-checkbox v-if="to_choose_user_list.length>0" :disabled="to_choose_user_disabled" style="width:100%;border:1px solid white" v-model="allChecked" @change="allSelect" label="全选" border></el-checkbox>
			  	  		</div>
                <div v-if="to_choose_user_list.length==0" style="text-align: center;color:#9FA0A2;margin-top:50px">当前部门没有用户</div>
				  	  	<div style="padding:2px 10px;" v-for="(item,index) in to_choose_user_list">
                  <el-checkbox :disabled="to_choose_user_disabled&&!item.checked" style="width:100%" v-model="item.checked" @change="userSelect(item)" :label="item.username" border></el-checkbox>
				  	  	</div>
				  	  </div>
				  	  <div v-if="index=='role'" style="margin-top:20px">
				  	  	  <div v-if="role_index" style="height:340px;overflow:auto">
				  	  	    <div v-for="item in roles" style="padding:2px 0px;">
				  	  	  	  <el-button @click="chooseRole(item)" style="width:100%;border:none;text-align:left"><i class="el-icon-user-solid"></i> {{item.role_name}}</el-button>
				  	  	    </div>
				  	  	  </div>
				  	  	  <div v-if="!role_index"><el-button type="text" @click="role_index=true">返回角色列表</el-button></div>
				  	  	  <div v-if="!role_index" style="height:320px;overflow:auto">
                    <div style="padding:2px 10px;">
                      <el-checkbox v-if="to_choose_user_list.length>0" :disabled="to_choose_user_disabled" style="width:100%;border:1px solid white" v-model="allChecked" @change="allSelect" label="全选" border></el-checkbox>
                    </div>
                    <div v-if="to_choose_user_list.length==0" style="text-align: center;color:#9FA0A2;margin-top:50px">当前角色下没有用户</div>
                    <div style="padding:2px 10px;" v-for="(item,index) in to_choose_user_list">
                      <el-checkbox :disabled="to_choose_user_disabled&&!item.checked" style="width:100%" v-model="item.checked" @change="userSelect(item)" :label="item.username" border></el-checkbox>
                    </div>
				  	  	  </div>
				  	  </div>
				  </el-col>
				  <el-col :span="12" style="padding-left:10px;height:390px;overflow:auto" v-if="diy">
              <div style="padding:2px 10px;">
                <el-checkbox v-if="to_choose_user_list.length>0" :disabled="to_choose_user_disabled" style="width:100%;border:1px solid white" v-model="allChecked" @change="allSelect" label="全选" border></el-checkbox>
              </div>
		  	  		<div v-if="to_choose_user_list.length==0" style="text-align: center;color:#9FA0A2;margin-top:50px">当前没有指定可选用户</div>
              <div style="padding:2px 10px;" v-for="(item,index) in to_choose_user_list">
                <el-checkbox :disabled="to_choose_user_disabled&&!item.checked" style="width:100%" v-model="item.checked" @change="userSelect(item)" :label="item.username" border></el-checkbox>
              </div>
				  </el-col>
			  </el-row>
		  </template>
	      <template #footer>

	      </template>
		</vxe-modal>`

  var div = document.createElement('div')
  div.setAttribute('id', 'ray_component_div')
  div.innerHTML = domStr
  document.body.appendChild(div)

  function removeDiv() {
    document.body.removeChild(div)
  }

  return new Promise((resolve, reject) => {
    new Vue({
      el: '#selectUser',
      data: {
        showFlag: true,
        selectNum: 0,
        allowNum: 1, //最大可选数量
        users: [], //搜索用户列表
        state: '',
        selectUsers: [], //已选用户列表
        index: 'index',
        myDpts: [], //我的部门列表
        dpt: {}, //右侧当前部门
        c_dpts: [], //子部门列表
        to_choose_user_list: [], //当前可选用户列表
        to_choose_user_disabled: false, //可选
        roles: [], //角色列表
        role_index: true, //角色主页
        guide: [], //导航栏
        diy: false, //是否指定可选择用户列表
        diy_userids: [], //指定的可选择用户userids['test','test1','test2']
        header: '',
        allChecked: false,
        confirmStatu: true,
        confirmButtonClick: false
      },
      watch: {
        selectUsers: function() {
          this.selectNum = this.selectUsers.length;
          if (this.selectNum >= this.allowNum) {
            this.to_choose_user_disabled = true;
          } else {
            this.to_choose_user_disabled = false;
          }
          if (this.selectUsers.length > 0) {
            this.confirmStatu = false;
            if (!this.to_choose_user_disabled) {
              this.allChecked = true;
              for (var i = 0; i < this.to_choose_user_list.length; i++) {
                var _this = this;
                this.selectUsers.forEach(function(item) {
                  if (_this.to_choose_user_list[i].id == item.id) {
                    _this.to_choose_user_list[i].checked = true;
                  }
                });
                if (!this.to_choose_user_list[i].checked) {
                  this.allChecked = false;
                }
              }
            }
          } else {
            this.confirmStatu = true;
          }
        }
      },
      mounted() {
        const {
          allowNum,
          select_userids,
          diy,
          diy_userids
        } = params
        this.allowNum = allowNum
        if (select_userids.length > 0) {
          api.getUsersByIds(select_userids).then(res => {
            this.selectUsers = res.list;
          })
        }
        if (diy) {
          this.diy = diy;
          this.diy_userids = diy_userids;
          this.getUsersByIds();
        } else {
          this.getMyDpts();
        }
      },
      methods: {
        confirm() {
          removeDiv();
          resolve(this.selectUsers);
        },
        close() {
          removeDiv();
        },
        //搜索用户
        querySearch(queryString, cb) {
          api.getUserByKeywords(queryString).then(res => {
            cb(res.list);
          })
        },
        //搜索用户选择事件
        handleSelect(item) {
          var flag = true;
          var _this = this;
          Object.keys(this.selectUsers).forEach((key) => {
            if (item.userid == _this.selectUsers[key].userid) {
              flag = false;
              return;
            }
          })
          if (flag) {
            if (this.selectUsers.length == this.allowNum) {
              this.$message.info("超出可选用户数量");
              return;
            }
            this.selectUsers.push(item);
            //已选列表默认勾选
            for (var i = 0; i < this.to_choose_user_list.length; i++) {
              var _this = this;
              this.selectUsers.forEach(function(item) {
                if (_this.to_choose_user_list[i].id == item.id) {
                  _this.to_choose_user_list[i].checked = true;
                }
              });
            }
          } else {
            this.$message.info("该用户已选择");
          }
        },
        //右侧用户列表选择事件
        userSelect(item) {
          if (item.checked) {
            var flag = true;
            Object.keys(this.selectUsers).forEach((key) => {
              if (item.userid == this.selectUsers[key].userid) {
                flag = false;
                return;
              }
            })
            if (flag) {
              this.selectUsers.push(item);
            } else {
              item.checked = false;
              this.$message.info("该用户已选择");
            }
          } else {
            let user = this.selectUsers.findIndex(i => {
              if (i.id == item.id) {
                return true
              }
            })
            this.selectUsers.splice(user, 1)
            this.allChecked = false;
          }
        },
        //全选
        allSelect(flag) {
          if (flag) {
            for (var i = 0; i < this.to_choose_user_list.length; i++) {
              var flag = true;
              var _this = this;
              Object.keys(this.selectUsers).forEach((key) => {
                if (_this.to_choose_user_list[i].userid == _this.selectUsers[key].userid) {
                  flag = false;
                  return;
                }
              })
              if (flag) {
                if (this.selectUsers.length == this.allowNum) {
                  return;
                }
                this.selectUsers.push(this.to_choose_user_list[i]);
                this.to_choose_user_list[i].checked = true;
              }
            }
          } else {
            for (var i = 0; i < this.to_choose_user_list.length; i++) {
              let user = this.selectUsers.findIndex(item => {
                if (item.id == this.to_choose_user_list[i].id) {
                  return true
                }
              })
              this.selectUsers.splice(user, 1)
              this.to_choose_user_list[i].checked = false;
            }
          }
        },
        //获取我的部门列表
        getMyDpts() {
          api.getMydpts().then(res => {
            this.myDpts = res.dpts;
          })
        },
        //根据部门编号获取当前部门用户列表和子部门列表
        getDptsByNo(no, type, index) {
          api.getDptsByNo(no).then(res => {
            this.dpt = res.dpt;
            this.c_dpts = res.c_dpts;
            this.to_choose_user_list = res.to_choose_user_list;
            if (type == 'add') {
              this.guide.push(this.dpt);
            } else if (type == 'del') {
              this.guide.splice(index + 1, 9999);
            }
            //已选列表默认勾选
            this.allChecked = true;
            for (var i = 0; i < this.to_choose_user_list.length; i++) {
              var _this = this;
              this.selectUsers.forEach(function(item) {
                if (_this.to_choose_user_list[i].id == item.id) {
                  _this.to_choose_user_list[i].checked = true;
                }
              });
              if (!this.to_choose_user_list[i].checked) {
                this.allChecked = false;
              }
            }
          })
        },
        //获取角色列表
        getRoles() {
          api.getRoles().then(res => {
            this.roles = res.list
          })
        },
        //选择角色获取角色下用户列表
        chooseRole(item) {
          api.getUserByRole(item.role_no).then(res => {
            this.to_choose_user_list = res.list;
            this.role_index = false;
            //已选列表默认勾选
            this.allChecked = true;
            for (var i = 0; i < this.to_choose_user_list.length; i++) {
              var _this = this;
              this.selectUsers.forEach(function(item) {
                if (_this.to_choose_user_list[i].id == item.id) {
                  _this.to_choose_user_list[i].checked = true;
                }
              });
              if (!this.to_choose_user_list[i].checked) {
                this.allChecked = false;
              }
            }
          })
        },
        //获取指定可选用户列表
        getUsersByIds() {
          api.getUsersByIds(this.diy_userids).then(res => {
            this.to_choose_user_list = res.list;
            //已选列表默认勾选
            this.allChecked = true;
            for (var i = 0; i < this.to_choose_user_list.length; i++) {
              this.selectUsers.forEach(function(item) {
                if (this.to_choose_user_list[i].id == item.id) {
                  this.to_choose_user_list[i].checked = true;
                }
              });
              if (!this.to_choose_user_list[i].checked) {
                this.allChecked = false;
              }
            }
          })
        },
        zzjg() {
          this.index = 'dpt';
          this.header = "按组织架构选择"
          this.guide = [];
          this.getDptsByNo(null, 'add', null);
        },
        indexDpt(no) {
          this.index = 'dpt';
          this.header = "按我所在部门选择"
          this.guide = [];
          this.getDptsByNo(no, 'add', null);
        },
        indexRole() {
          this.index = 'role';
          this.header = "按角色选择"
          this.role_index = true;
          this.getRoles();
        },
        //部门下一级
        down(no) {
          this.getDptsByNo(no, 'add', null);
        },
        //导航点击
        gudieClick(no, index) {
          this.getDptsByNo(no, 'del', index);
        },
        goBack() {
          this.index = 'index';
        },
        //删除已选择用户
        handleClose(tag) {
          this.selectUsers.splice(this.selectUsers.indexOf(tag), 1);
          //已选列表默认勾选
          for (var i = 0; i < this.to_choose_user_list.length; i++) {
            if (tag.id == this.to_choose_user_list[i].id) {
              this.to_choose_user_list[i].checked = false;
            }
          }
          this.allChecked = false;
        },
      }
    })
  });

}

export default {
  show
}
